package com.dmcb.trade.business.crawlers.author;

import com.dmcb.common.business.constants.CommonConstant;
import com.dmcb.common.business.utils.JsonUtil;
import com.dmcb.common.business.utils.ListUtil;
import com.dmcb.common.business.utils.WebUtil;
import com.dmcb.common.web.conversion.JsonResult;
import com.dmcb.trade.business.constants.CrawlConstant;
import com.dmcb.trade.business.crawlers.article.BaiDuBaiJiaParser;
import com.dmcb.trade.business.entities.Article;
import com.dmcb.trade.business.entities.Author;
import com.dmcb.trade.business.mappers.ArticleCrawlMapper;
import org.apache.commons.lang3.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

/**
 * 百度百家所有文章解析
 * Created by Administrator on 2016/7/21.
 */
@Service
public class BaijiaCrawler extends BaseCrawler {
    Logger logger = LoggerFactory.getLogger(JianshuCrawler.class);

    @Autowired
    private BaiDuBaiJiaParser baiDuBaiJiaParser;
    @Autowired
    private ArticleCrawlMapper articleCrawlMapper;

    @Override
    protected String url() {
        return CrawlConstant.BAIDUBAIJIA_URL;
    }

    @Override
    protected int tag() {
        return CrawlConstant.BAIDUBAIJIA_TAG;
    }

    @Override
    protected String avatarSelect() {
        return "div.author-pic>img";
    }

    @Override
    protected String channelNameSelect() {
        return "div.author-name";
    }

    @Override
    protected String authorLink() {
        return "div.info>p>a";
    }

    @Override
    protected String listSelect() {
        return "div.feeds>div";
    }

    @Override
    protected String titleSelect() {
        return "div.feeds-item>h3>a";
    }

    @Override
    protected String authorSelect() {
        return "div.author-name";
    }

    @Override
    protected JsonResult crawl(int authorId, String link, Author author, Document doc, boolean all) {
        // 爬取文章
        int page = 1;
        int totalAll = 0;
        doc = Jsoup.parse(webClientUtil.getPage(link).asXml(), baseUrl(link));
        String js = doc.select("script").last().html();
        String baijiaAiD = js.substring(js.indexOf("authorid:"), js.indexOf("artical_list_num")).replace("authorid:","").trim().replace(",", "").replace("'", "");
        int id = Integer.parseInt(baijiaAiD);
        while (page <= CrawlConstant.CRAWL_PAGE_TOTAL) {
            String json = WebUtil.buildRequest(link + "ajax/authorlatestarticle?page=" + page + "&pagesize=20&authorid=" + id + "&prevarticalid=507936",false);
            page++;
            JsonResult result = baiJiaIterate(authorId, json);
            if (!result.isSuccess()) {
                return result;
            }
            totalAll += result.getInt();
            if (!all && result.getInt() < 8) {
                break;
            }

        }
        return totalAll == 0 ? error(CrawlConstant.MSG_WARN_NO_UPDATE) : success(totalAll);
    }

    /**
     * 迭代解析、保存文章
     *
     * @return 成功保存数量
     */
    protected JsonResult baiJiaIterate(int authorId, String json) {
        List<Map<String, String>> listResult = JsonUtil.readListResult(json);
        if (ListUtil.isEmpty(listResult) || listResult.size() == 0) {
            return success(0);

        }
        int succ = 0;
        int exist = 0;
        for (Map<String, String> map : listResult) {
            String title = WebUtil.URLDecode(map.get("m_title"));
            if (StringUtils.isBlank(title)) {
               continue;
            }
            try {
                // 校验作者、标题是否已存在
                Article article = articleCrawlMapper.queryByAuthorTitle(authorId, title);
                if (article != null) {
                    exist++;
                    if (exist >= 6 && succ == 0) {
                        return success(0);
                    }
                    continue;
                }
                String href = map.get("m_display_url");
                JsonResult result = parse(authorId, href);
                succ += result.isSuccess() ? 1 : 0;
            } catch (Exception e) {
                logger.error("Parser.parse error,{}", map.toString(), e);
                return error(CommonConstant.ABNORMAL_MSG);
            }
        }
        return success(succ);
    }


    @Override
    protected JsonResult iterate(int authorId, Document doc) {
        return super.iterate(authorId, doc);
    }

    @Override
    protected JsonResult parse(int authorId, String link) throws Exception {
        return baiDuBaiJiaParser.parse(authorId, link);
    }

    @Override
    protected String getBody(Document doc) {
        return baiDuBaiJiaParser.getBody(doc);
    }
}

